package org.bling.star.server.adapter.impl;

import org.bling.star.common.connection.IDbConnection;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @Describe: 获取不同的SPI接口
 * @Date: 2024/7/19
 * @Author: szz
 */
public class AdapterContextManager {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(AdapterContextManager.class);
    private final List<Object> adapters = new ArrayList<>();
    public AdapterContextManager() {
    }
    public static AdapterContextManager getInstance() {
        AdapterContextManager adapterContextManager = new AdapterContextManager();
        //可以configuration获取，先不写
        adapterContextManager.init(IDbConnection.class);
        return adapterContextManager;
    }
    public <T> void init(Class<T> serviceClass) {
//        AccessController.doPrivileged(new PrivilegedAction<Void>() {
//            public Void run() {
                ServiceLoader<T> load = ServiceLoader.load(serviceClass);
                Iterator<T> iterator = load.iterator();
                try {
                    while (iterator.hasNext()) {
                        T next = iterator.next();
                        adapters.add(next);
                    }
                }catch (Exception e) {
                    log.error("loader can't load interface:{}",serviceClass.getName());
                }
//                return null;
//            }
//        });
    }

    public <T> T getAdapter(Class<T> serviceClass) {
        for (Object adapter : adapters) {
            if(serviceClass.isInstance(adapter)) {
                return (T)adapter;
            }
        }
        return null;
    }
}
